<script setup>
import { reactive, ref, onMounted } from 'vue';
import { getList } from "@/api/index.js";
import { useCounterStore } from "@/stores/counter";
import { toFormat } from "@/utils"
const store = useCounterStore();
// const value1 = ref('');
let list = reactive([
])
const isLoading = ref(false);
const finished = ref(false);
const show_calendar = ref(false);
const date = ref('选择时间');
const error = ref(false);
const minDate =ref(new Date("2024","01","01"));
const maxDate =ref(new Date("2034","01","01"));
let y = new Date().getFullYear();
let m = new Date().getMonth() + 1;
const currentDate = ref([y, m]);
const columnsType = ['year', 'month'];
const form = reactive({
    size: 10,
    page: 1,
    endDate: '',
    startDate: '',
    studentId: ''
});
const dicName = [
    { id: 'CREATED', name: "已创建" },
    { id: 'PAID', name: "已支付" },
    { id: 'CANCELLED', name: "已取消" },
]
const arrConsumpName = [
    { id: 'PENDING', name: "待消费" },
    { id: 'CONSUMED', name: "已消费" },
    { id: 'REFUNDED', name: "已退款" },
]
const getName = (k) => {
    let r = dicName.find(it => it.id === k)
    return r && r.name ? r.name : '';
}
const getNameConsump = (k) => {
    let r = arrConsumpName.find(it => it.id === k)
    return r && r.name ? r.name : '';
}
const onLoad = () => {
    isLoading.value = true;
    // 异步更新数据
    let param = { ...form };
    let dates = getMonthDateRange(currentDate.value[0]+'-'+currentDate.value[1]);
    param.startDate = dates[0]
    param.endDate = dates[1]
    for (let k in param) {
        if (!param[k]) delete param[k];
    }
    getList(param).then(
        rs => {
            if (rs.code == 200 && rs.data && rs.data.content.length) {
                let arr = rs.data.content;
                for (let i = 0; i < arr.length; i++) {
                    list.push(arr[i])
                }
                form.page++;
            }
            isLoading.value = false;
            if (rs.data.content.length < form.size) {
                finished.value = true;
            }
        }
    ).catch(
        err => {
            isLoading.value = false;
            error.value = true;
        }
    )
};
const  getMonthDateRange = (yearMonthStr)=> {
    // 解析年份和月份
    const [year, month] = yearMonthStr.split('-').map(Number);

    // 创建月份第一天的日期对象
    const firstDay = new Date(year, month - 1, 1);

    // 获取月份的最后一天，这里我们利用Date对象在月份加一时会自动调整到下个月第一天的特性
    // 然后减一得到本月的最后一天
    const lastDay = new Date(year, month, 0).getDate();

    // 构造从第一天到最后一天的日期数组
    // 注意：我们需要将每一天都转换成新的Date对象，因为Date对象在JavaScript中是可变的
    // 并且我们希望数组中的每个元素都是独立的
    const dateRange = [];
    dateRange.push(new Date(year, month - 1, 1));
    dateRange.push(new Date(year, month - 1, lastDay));

    // 如果需要将Date对象转换为字符串格式（如'YYYY-MM-DD'），可以在这里进行
    // 示例：将数组中的每个Date对象转换为'YYYY-MM-DD'格式的字符串
    const dateRangeStr = dateRange.map(date =>
        `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)}`
    );

    // 返回数组（这里我们直接返回Date对象数组，如果你需要字符串数组，请取消上面注释的转换部分）
    return dateRangeStr;
}
const formatDate = (date) => `${date.getMonth() + 1}/${date.getDate()}`;
const onConfirm = (values) => {
    const [start, end] = values;
    show_calendar.value = false;
    date.value = `${formatDate(start)} - ${formatDate(end)}`;
    form.endDate = end ? toFormat('YYYY-MM-DD', end) : '';
    form.startDate = start ? toFormat('YYYY-MM-DD', start) : '';
    form.page = 1;
    list = [];
    onLoad();
};

const confirmDate = () =>{
    show_calendar.value = false;
    form.page = 1;
    list = [];
    onLoad();
}
onMounted(
    () => {
        if (store.userInfo && store.userInfo.number) {
            form.studentId = store.userInfo.number;
            onLoad();
        }

    }
)


</script>

<template>
    <!-- <van-overlay class-name="flex justify-center items-center" :show="isLoading">
        <van-loading type="spinner" color="#1989fa" />
    </van-overlay> -->
    <!-- <van-nav-bar title="充值记录" left-text="返回" left-arrow @click-left="onClickLeft" fixed placeholder
        safe-area-inset-top /> -->
    <div style="min-height: 60vh;" class="mx-4 p-4 bg-white rounded-xl my-3">
        <div class="flex items-center justify-between text-black">
            <div class="text-base font-bold">充值记录</div>

            <div class="text-sm font-bold" @click="show_calendar = true">{{ currentDate[0] + '-'+ currentDate[1] }}<van-icon name="filter-o" /></div>
        </div>
        <van-list :immediate-check="false" :offset="60" v-model:loading="isLoading" v-model:error="error"
            :finished="finished" finished-text="没有更多了" @load="onLoad">
            <div v-for="item in list" :key="item.id" class="mt-4 text-sm">
                <div class="flex justify-between">
                    <span style="color: #0E100F;" class="text-base font-semibold">订单号:<span class="ml-1">{{
                            item.businessOrderNo }}</span></span>
                    <span v-if="item.orderStatus" style="color: #F8690A ;" class="text-sm">{{ getName(item.orderStatus)
                        }}</span>

                </div>
                <div style="color: #838788 ;" class="flex mt-3 justify-between">
                    <div>
                        <span>充值时间:</span>
                        <span class="ml-1">{{ toFormat('YYYY-MM-DD hh:mm:ss', item.createTime) }}</span>
                    </div>
<!--                    <span v-if="item.consumptionStatus" style="color: #F8690A ;" class="text-sm ml-2">{{-->
<!--                        getNameConsump(item.consumptionStatus) }}</span>-->
                </div>
                <div style="color: #838788 ;" class="flex mt-3">
                    <span>充值金额:</span>
                    <span style="color:#FF2121" class="font-bold ml-1">{{ item.orderAmount }}</span>
                </div>

                <div class="mt-4" style="background-color: #D8D8D8;height: 1px;opacity: 0.3;"></div>
            </div>
        </van-list>
    </div>
    <van-popup
  v-model:show="show_calendar"
  position="bottom"
  :style="{ height: '50%' }"
>
<van-date-picker
  v-model="currentDate"
  @confirm = "confirmDate"
  @cancel = "show_calendar = false"
  title="选择年月"
  :filter="filter"
  :min-date="minDate"
  :max-date="maxDate"
  :columns-type="columnsType"
/>
</van-popup>
    <!-- <van-calendar v-model:show="show_calendar" switch-mode="month" type="range" @confirm="onConfirm" /> -->
</template>
